<template>
  <div class="notice-container">
    <!-- <el-card> -->
    <div class="addNotice">
      <el-button
        type="primary"
        v-if="currentUserInfo.role == '管理员'"
        @click="addDialogVisible = true"
        >添加公告</el-button
      >
    </div>

    <!-- </el-card> -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="center" inline class="demo-table-expand">
            <el-form-item label="商品描述">
              <div>{{ props.row.desc }}</div>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="公告标题" prop="title"> </el-table-column>
      <el-table-column label="发布人" prop="username"> </el-table-column>
      <el-table-column label="发布日期" prop="datetime"> </el-table-column>
      <el-table-column label="操作" v-if="currentUserInfo.role == '管理员'">
        <template slot-scope="scope">
          <el-button type="primary" @click="editNotice(scope.row.id)"
            >修改</el-button
          >
          <el-button type="delete" @click="delNotice(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加订单的对话框 -->
    <el-dialog
      title="添加公告"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主题区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="80px"
      >
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="addForm.title"></el-input>
        </el-form-item>
        <el-form-item label="发布人" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="发布日期" prop="Notice_date">
          <!-- <el-input v-model="addForm.Notice_date"></el-input> -->
          <el-date-picker
            v-model="addForm.datetime"
            type="datetime"
            placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 5 }"
            v-model="addForm.desc"
          ></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addNotice">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改公告的对话框 -->
    <el-dialog
      title="修改公告"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 内容主题区域 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="80px"
      >
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="editForm.title"></el-input>
        </el-form-item>
        <el-form-item label="发布人" prop="username">
          <el-input v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="发布日期" prop="Notice_date">
          <!-- <el-input v-model="addForm.Notice_date"></el-input> -->
          <el-date-picker
            v-model="editForm.datetime"
            type="datetime"
            placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input type="textarea" v-model="editForm.desc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editNoticeInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Notice',
  data() {
    return {
      tableData: [],
      addForm: {
        title: '',
        username: '',
        datetime: '',
        desc: '',
      },
      addFormRules: {
        title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
        username: [
          { required: true, message: '请输入公告发布人名称', trigger: 'blur' },
        ],
        datetime: [
          { required: true, message: '请输入公告发布日期', trigger: 'blur' },
        ],
        desc: [{ required: true, message: '请输入公告描述', trigger: 'blur' }],
      },
      editForm: {},
      editFormRules: {
        title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
        username: [
          { required: true, message: '请输入公告发布人名称', trigger: 'blur' },
        ],
        datetime: [
          { required: true, message: '请输入公告发布日期', trigger: 'blur' },
        ],
        desc: [{ required: true, message: '请输入公告描述', trigger: 'blur' }],
      },
      addDialogVisible: false,
      editDialogVisible: false,
    }
  },
  created() {
    this.getNoticeData()
  },
  computed: {
    currentUserInfo() {
      return this.$store.state.userInfo
    },
  },
  methods: {
    getNoticeData() {
      this.$http.get('/myApi/notice/noticeAll').then((res) => {
        if (res.data.code !== 200) {
          this.$message.error('获取公告信息失败')
        }
        this.$message.success('获取公告信息成功')
        this.tableData = res.data.data
      })
    },
    async editNotice(id) {
      // 根据传进来的id 发起 axios请求，得到对公告的信息
      const { data: res } = await this.$http.get('/myApi/notice/notice/' + id)
      console.log(res, '???????')
      if (res.code !== 200) {
        return this.$message.error('查询公告信息失败')
      }
      this.$message.success('查询公告信息成功')
      // 请求成功后将公告的信息保存到 data中
      this.editForm = res.data

      this.editDialogVisible = true
    },
    async delNotice(id) {
      // 弹框询问公告是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该公告, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err) // cancel
      // 如果公告点击确认 删除，则返回值为 字符串 confirm
      // 如果公告点击取消 删除，则返回值为 字符串 cancel
      // console.log(confirmResult) // Promise对象
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除!')
      }
      // console.log('确认了删除')
      const { data: res } = await this.$http.delete(
        '/myApi/notice/notice/' + id
      )

      if (res.code !== 200) {
        return this.$message.error('删除公告信息失败!')
      }
      this.$message.success('删除公告信息成功')
      // 重新渲染列表
      this.getNoticeData()
    },
    // 监听修改公告对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改公告信息并提交
    editNoticeInfo() {
      // validate()是提交前 对整个表单进行校验的方法
      this.$refs.editFormRef.validate(async (valid) => {
        // console.log(valid)
        if (!valid) return

        // 可以发起修改公告的网络请求
        const { data: res } = await this.$http.post(
          '/myApi/notice/notcie/' + this.editForm.id,
          this.editForm
        )
        console.log(res)
        if (res.code !== 200) {
          return this.$message.error('更新公告信息失败')
        }
        // 隐藏修改公告的对话框
        this.editDialogVisible = false
        // 重新渲染数据
        this.getNoticeData()
        // 提示修改成功
        this.$message.success('更新公告信息成功')
      })
    },
    // 监听添加订单对话框的关闭事件
    addDialogClosed() {
      // 拿到对话框的引用，调用自身的resetFields方法，重置表单
      this.$refs.addFormRef.resetFields()
    },
    // 添加订单信息
    addNotice() {
      this.$refs['addFormRef'].validate((valid) => {
        // 校验失败
        if (!valid) return console.log('添加订单信息失败!!')

        // this.addForm.Notice_date = this.addForm.Notice_date
        //   .split('')
        //   .splice(0, 10)
        //   .join('')
        // 添加订单信息
        this.$http.post('/myApi/notice/addnotcie', this.addForm).then((res) => {
          console.log(res.data)
          if (res.data.code !== 200) {
            this.$message.warning('添加公告失败')
          } else {
            this.$message.success('添加公告成功')
            // 隐藏添加订单的对话框
            this.addDialogVisible = false
            this.getNoticeData()
          }
        })
      })
    },
  },
}
</script>

<style lang="less" scoped>
// .notice-container {
//   display: flex;
//   justify-content: flex-start;
// }
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
